<?
  /**
   * CFD_CAP_Vehicles - access CAPNetwork.co.uk api
   * 
  **/
  class CFD_CAP_Vehicles extends CFD_CAP
  {
    public function getUsedValuesForIDYearMonthMileage($capId, $year, $month, $mileage)
	{
	  $sp = new Zend_Soap_Client(self::VehEstimation_WSDL);

	  //$url = "http://webservices.capnetwork.co.uk/capusedvalues_webservice/capusedvalues.asmx/GetUsedValuesForIDYearMonthMileage?Subscriber_ID=".self::subscriberId."&Password=".self::password."&Database=CAR&CAPID=".$capId."&UsedValuesDate=".urlencode(date("Y/m/d"))."&JustCurrent=true&Year=".$year."&Month=".$month."&Mileage=".$mileage;

	 
	  $vehicle = $sp->GetUsedValuesForIDYearMonthMileage( array(	'Subscriber_ID' => self::subscriberId,
	  				 												'Password' => self::password,
	  				 												'Database' => 'CAR',
																	'CAPID' => $capId,
																	'UsedValuesDate' => date('Y-m-d'),
																	'JustCurrent' => true, 
																	'Year' => $year, 
																	'Month' => $month, 
																	'Mileage' => $mileage) );

	  return $vehicle->GetUsedValuesForIDYearMonthMileageResult;
	}

    public function vehicleImage($capId, $width = 260, $height = 220)
	{
	   $headers[] = "Content-Type: application/x-www-form-urlencoded";

	   $params = "SUBID=161396&PWD=568e7s7H&DB=CAR&CAPID={$capId}&DATE=24%2F09%2F2013&WIDTH={$width}&HEIGHT={$height}&IMAGETEXT=&VIEWPOINT=";
	   $ch = curl_init(); 
	   curl_setopt($ch, CURLOPT_URL, "http://images.capnetwork.co.uk/VehicleImage.aspx");   
	   curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	   curl_setopt($ch, CURLOPT_POST, 1);
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
	   $return = curl_exec($ch); 

	   $information = curl_getinfo($ch);

	   if (strpos($return, "<!DOCTYPE html PUBLIC") !== false)
	     return substr($return, 0, strpos($return, "<!DOCTYPE html PUBLIC"));
	   else
	     return $return;
	}

    public function capToArray(SimpleXMLElement $xml)
	{
        $array = (array)$xml;

        foreach ( array_slice($array, 0) as $key => $value )
		{
            if ( $value instanceof SimpleXMLElement) {
                $array[$key] = empty($value) ? NULL : $this->capToArray($value);
            }
			elseif (is_array($value))
			{ 
			  foreach ($value as $k => $v)
            	if ( $v instanceof SimpleXMLElement) 
                  $array[$key][$k] = empty($v) ? NULL : $this->capToArray($v);
			}
        }
        return $array;
    }

    public function DVLALookupVRM($vrm)
	{
	  $sp = new Zend_Soap_Client(self::Dvla_WSDL);

	  $vehicle = $sp->DVLALookupVRM( array(	'SubscriberID' => self::subscriberId,
	  				 						'Password' => self::password,
	  				 						'vrm' => $vrm) );


	  $data = $vehicle->DVLALookupVRMResult->any;
	  //file_put_contents("/tmp/vrm2", $data);
	  //$data = file_get_contents("/tmp/vrm2");
	  $sObj = simplexml_load_string($data);

	  return $this->capToArray($sObj);
	}

    public function GetCAPRange($brand, $load_from_db = true)
	{
	  $carModelsTable = new Application_Model_CarModels();

	  if ($load_from_db)
	    return $carModelsTable->fetchAll($carModelsTable->select()->where('car_brands_id = ?', $brand->id));

	  $sp = new Zend_Soap_Client(self::Vehicles_WSDL);

	  $ranges = $sp->GetCAPRange( array(	'Subscriber_ID' => self::subscriberId,
	  				 					'Password' => self::password,
	  				 					'Database' => "CAR",
	  				 					'ManCode' => $brand->id,
	  				 					'JustCurrentRanges' => false,
	  				 					'BodyStyleFilter' => ""));
	  
	  preg_match_all("/<CRan_Code>(.*?)<\/CRan_Code><CRan_Name>(.*?)<\/CRan_Name>/i", $ranges->GetCAPRangeResult->Returned_DataSet->any, $result, PREG_SET_ORDER);

	  // CACHE THE RESULTS IN THE DATABASE
	  foreach ($result as $res)
	  {
	    $carBrandRow = $carModelsTable->createRow();
	    $carBrandRow->id = $res[1];
	    $carBrandRow->car_brands_id = $brand->id;
	    $carBrandRow->name = $res[2];

	    try
	    {
	      $carBrandRow->save();
	    }
	    catch (Exception $e)
	    {
	    
	    }
	  }

	  return $carModelsTable->fetchAll($carModelsTable->select()->where('car_brands_id = ?', $brand->id));
	}

    /**
     * GetCAPMan 
     * 
     * @param mixed $load_from_db 
     * @access public
     * @return void
    **/
    public function GetCAPMan($load_from_db = true)
	{
	  $carBrandsTable = new Application_Model_CarBrands();

	  if ($load_from_db)
	    return $carBrandsTable->fetchAll();

	  $sp = new Zend_Soap_Client(self::Vehicles_WSDL);

	  $vehicles = $sp->GetCAPMan( array(	'Subscriber_ID' => self::subscriberId,
					 						'Password' => self::password,
					 						'Database' => "CAR",
					 						'JustCurrentManufacturers' => false,
					 						'BodyStyleFilter' => ""));

	  preg_match_all("/<CMan_Code>(.*?)<\/CMan_Code><CMan_Name>(.*?)<\/CMan_Name>/i", $vehicles->GetCAPManResult->Returned_DataSet->any, $result, PREG_SET_ORDER);

	  // CACHE THE RESULTS IN THE DATABASE
	  foreach ($result as $res)
	  {
		$carModelRow = $carBrandsTable->createRow();
		$carModelRow->id = $res[1];
		$carModelRow->name = $res[2];

		try
		{
		  $carModelRow->save();
		}
		catch (Exception $e)
		{
		
		}
	    
	  }
	  return $carBrandsTable->fetchAll();
	}
  }
